use axum::{
    extract::{Path, State},
    http::StatusCode,
    routing::{delete, get, post, put},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use time::OffsetDateTime;
use tracing::info;

use crate::modules::*;
use crate::modules::config;

// 模块化应用状态
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AppState {
    pub database: Arc<Database>,
    pub user_management: Arc<UserManagement>,
    pub gateway_service: Arc<GatewayService>,
    pub menu_management: Arc<MenuManagement>,
    pub communication_manager: Arc<CommunicationManager>,
    pub hot_reload_service: Arc<HotReloadService>,
}

mod modules;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    info!("🚀 模块化网关管理系统启动中...");

    // 加载配置文件
    let app_config = config::load_config()?;
    info!("📋 配置文件加载完成: 端口 {}, 主机 {}", app_config.server.port, app_config.server.host);

    // 初始化日志系统
    tracing_subscriber::fmt::init();
    info!("📋 日志系统初始化完成");

    // 创建数据库实例
    let database = Arc::new(Database::new(&app_config.database));
    info!("🗄️ 数据库模块初始化完成");

    // 创建用户管理模块
    let user_management = Arc::new(UserManagement::new(database.as_ref().clone(), &app_config.auth));
    info!("👥 用户管理模块初始化完成");

    // 创建网关服务模块
    let gateway_service = Arc::new(GatewayService::new(&app_config.gateway));
    info!("🌐 网关服务模块初始化完成");

    // 创建菜单管理模块
    let menu_management = Arc::new(MenuManagement::new(database.as_ref().clone()));
    info!("📊 菜单管理模块初始化完成");

    // 创建通信管理器
    let communication_manager = Arc::new(CommunicationManager::new());
    info!("📡 通信管理器初始化完成");

    // 注册服务到注册中心
    let service_registry = communication_manager.get_service_registry();
    service_registry.register_service(ServiceInfo {
        service_name: "user_management".to_string(),
        service_url: app_config.services.user_management_url.clone(),
        health_check_url: app_config.services.user_management_health_url.clone(),
        version: "1.0.0".to_string(),
        metadata: serde_json::json!({}),
    });

    service_registry.register_service(ServiceInfo {
        service_name: "gateway_service".to_string(),
        service_url: app_config.services.gateway_url.clone(),
        health_check_url: app_config.services.gateway_health_url.clone(),
        version: "1.0.0".to_string(),
        metadata: serde_json::json!({}),
    });

    service_registry.register_service(ServiceInfo {
        service_name: "menu_management".to_string(),
        service_url: app_config.services.menu_url.clone(),
        health_check_url: app_config.services.menu_health_url.clone(),
        version: "1.0.0".to_string(),
        metadata: serde_json::json!({}),
    });

    // 创建热加载服务
    let config_path = PathBuf::from("config/gateway_config.json");
    let rules_path = PathBuf::from("config/route_rules.json");
    
    // 确保配置目录存在
    if let Some(parent) = config_path.parent() {
        tokio::fs::create_dir_all(parent).await.map_err(|e| {
            anyhow::anyhow!("Failed to create config directory: {}", e)
        })?;
    }
    
    let hot_reload_service = Arc::new(HotReloadService::new(config_path, rules_path)?);
    info!("🔄 热加载服务初始化完成");

    // 设置网关服务到热加载服务
    hot_reload_service.set_gateway_service(gateway_service.clone()).await;

    // 启动热加载服务
    hot_reload_service.start_service().await.unwrap();
    info!("✅ 热加载服务启动完成");

    // 创建应用状态
    let app_state = AppState {
        database,
        user_management,
        gateway_service,
        menu_management,
        communication_manager,
        hot_reload_service,
    };

    // 启动通信系统
    communication_manager.start().await;
    info!("✅ 通信系统启动完成");

    // 初始化示例数据
    initialize_sample_data(database.clone()).await;

    // 创建应用路由
    let app = Router::new()
        // 健康检查
        .route("/health", get(health_check))
        
        // 用户管理API
        .route("/api/v1/users", get(list_users))
        .route("/api/v1/users", post(create_user))
        .route("/api/v1/users/:id", get(get_user))
        .route("/api/v1/users/:id", put(update_user))
        .route("/api/v1/users/:id", delete(delete_user))
        
        // 认证API
        .route("/api/v1/auth/login", post(login))
        .route("/api/v1/auth/register", post(register))
        
        // 网关API
        .route("/api/v1/gateway/routes", get(get_routes))
        .route("/api/v1/gateway/routes", post(create_route))
        .route("/api/v1/gateway/routes/:id", delete(delete_route))
        
        // 菜单API
        .route("/api/v1/menus", get(list_menus))
        .route("/api/v1/menus", post(create_menu))
        .route("/api/v1/menus/tree", get(get_menu_tree))
        .route("/api/v1/menus/:id", get(get_menu))
        .route("/api/v1/menus/:id", put(update_menu))
        .route("/api/v1/menus/:id", delete(delete_menu))
        
        // 通信系统API
        .route("/api/v1/communication/services", get(list_services))
        .route("/api/v1/communication/health", get(health_check_services))
        
        .with_state(Arc::new(app_state));

    // 启动服务器
    let addr = SocketAddr::from(([0, 0, 0, 0], app_config.server.port));
    info!("✅ 服务器启动在: {}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

// 健康检查处理器
#[axum::debug_handler]
async fn health_check() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "status": "healthy",
        "service": "gateway-management-system",
        "timestamp": OffsetDateTime::now_utc().unix_timestamp()
    }))
}

// 初始化示例数据
async fn initialize_sample_data(db: Arc<Database>) -> anyhow::Result<()> {
    // 创建默认菜单
    let menu_ids = db.generate_menu_ids(2).await?;
    let menu1 = modules::database::Menu {
        id: menu_ids[0],
        parent_id: None,
        menu_name: "仪表板".to_string(),
        menu_path: Some("/".to_string()),
        menu_icon: Some("home".to_string()),
        menu_type: "menu".to_string(),
        sort_order: 0,
        is_visible: true,
        permissions: serde_json::json!({}),
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };
    let _dashboard_menu = db.add_menu(menu1).await?;
    
    let menu2 = modules::database::Menu {
        id: menu_ids[1],
        parent_id: None,
        menu_name: "网关配置".to_string(),
        menu_path: Some("/gateway".to_string()),
        menu_icon: Some("server".to_string()),
        menu_type: "menu".to_string(),
        sort_order: 1,
        is_visible: true,
        permissions: serde_json::json!({}),
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };
    let _gateway_menu = db.add_menu(menu2);
    
    let menu3 = modules::database::Menu {
        id: 3,
        parent_id: None,
        menu_name: "路由管理".to_string(),
        menu_path: Some("/routes".to_string()),
        menu_icon: Some("route".to_string()),
        menu_type: "menu".to_string(),
        sort_order: 2,
        is_visible: true,
        permissions: serde_json::json!({}),
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };
    let _routes_menu = db.add_menu(menu3);
    
    let menu4 = modules::database::Menu {
        id: 4,
        parent_id: None,
        menu_name: "用户管理".to_string(),
        menu_path: Some("/users".to_string()),
        menu_icon: Some("users".to_string()),
        menu_type: "menu".to_string(),
        sort_order: 3,
        is_visible: true,
        permissions: serde_json::json!({}),
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };
    let _users_menu = db.add_menu(menu4);
    
    let menu5 = modules::database::Menu {
        id: 5,
        parent_id: None,
        menu_name: "菜单管理".to_string(),
        menu_path: Some("/menus".to_string()),
        menu_icon: Some("menu".to_string()),
        menu_type: "menu".to_string(),
        sort_order: 4,
        is_visible: true,
        permissions: serde_json::json!({}),
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };
    let _menus_menu = db.add_menu(menu5);

    info!("示例数据初始化完成");
}

// 用户管理请求结构体
#[derive(Debug, Serialize, Deserialize)]
struct CreateUserRequest {
    username: String,
    password: String,
    email: String,
    role: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct UpdateUserRequest {
    username: Option<String>,
    email: Option<String>,
    role: Option<String>,
}

// 菜单请求结构体
#[derive(Debug, Serialize, Deserialize)]
struct CreateMenuRequest {
    name: String,
    path: String,
    icon: String,
    parent_id: Option<i64>,
    sort_order: i32,
}

#[derive(Debug, Serialize, Deserialize)]
struct UpdateMenuRequest {
    name: Option<String>,
    path: Option<String>,
    icon: Option<String>,
    parent_id: Option<i64>,
    sort_order: Option<i32>,
}

// 用户管理处理器
#[axum::debug_handler]
async fn list_users(
    State(state): State<Arc<AppState>>,
) -> Json<Vec<modules::database::User>> {
    Json(state.database.get_all_users())
}

#[axum::debug_handler]
async fn create_user(
    State(state): State<Arc<AppState>>,
    Json(request): Json<CreateUserRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    // 在实际应用中，这里应该对密码进行哈希处理
    let password_hash = format!("hashed_{}", request.password); // 简化处理
    
    let user = modules::database::User {
        id: 0,
        username: request.username,
        email: request.email,
        password_hash,
        full_name: None,
        phone: None,
        status: "active".to_string(),
        last_login: None,
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
        created_by: Some(1),
    };
    
    let user_id = state.database.add_user(user);
    
    Ok(Json(serde_json::json!({
        "success": true,
        "id": user_id,
        "message": "用户创建成功"
    })))
}

#[axum::debug_handler]
async fn get_user(
    State(state): State<Arc<AppState>>,
    Path(id): Path<i64>,
) -> Result<Json<modules::database::User>, StatusCode> {
    match state.database.get_user(id.try_into().unwrap()) {
        Some(user) => Ok(Json(user)),
        None => Err(StatusCode::NOT_FOUND),
    }
}

#[axum::debug_handler]
async fn update_user(
    State(state): State<Arc<AppState>>,
    Path(id): Path<i64>,
    Json(request): Json<UpdateUserRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    // 获取现有用户
    let user_id = id.try_into().unwrap();
    if let Some(mut user) = state.database.get_user(user_id) {
        // 更新用户信息
        if let Some(username) = request.username {
            user.username = username;
        }
        if let Some(email) = request.email {
            user.email = email;
        }
        user.updated_at = OffsetDateTime::now_utc();
        
        if state.database.update_user(user_id, user) {
            Ok(Json(serde_json::json!({
                "success": true,
                "message": "用户更新成功"
            })))
        } else {
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

#[axum::debug_handler]
async fn delete_user(
    State(state): State<Arc<AppState>>,
    Path(id): Path<i64>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    if state.database.delete_user(id.try_into().unwrap()) {
        Ok(Json(serde_json::json!({
            "success": true,
            "message": "用户删除成功"
        })))
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

// 认证处理器
#[axum::debug_handler]
async fn login() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "success": true,
        "message": "登录成功",
        "token": "sample_jwt_token"
    }))
}

#[axum::debug_handler]
async fn register() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "success": true,
        "message": "注册成功"
    }))
}

// 网关处理器
#[axum::debug_handler]
async fn get_routes() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "routes": [],
        "total": 0
    }))
}

#[axum::debug_handler]
async fn create_route() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "success": true,
        "message": "路由创建成功"
    }))
}

#[axum::debug_handler]
async fn delete_route(
    Path(id): Path<i64>,
) -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "success": true,
        "message": format!("路由删除成功: {}", id)
    }))
}

// 菜单处理器
#[axum::debug_handler]
async fn list_menus(
    State(state): State<Arc<AppState>>,
) -> Json<Vec<modules::database::Menu>> {
    Json(state.database.get_all_menus())
}

#[axum::debug_handler]
async fn create_menu(
    State(state): State<Arc<AppState>>,
    Json(request): Json<CreateMenuRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let menu = modules::database::Menu {
        id: 0,
        parent_id: request.parent_id.map(|id| id as i32),
        menu_name: request.name.clone(),
        menu_path: Some(request.path.clone()),
        menu_icon: Some(request.icon.clone()),
        menu_type: "menu".to_string(),
        sort_order: request.sort_order,
        is_visible: true,
        permissions: serde_json::json!({}),
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };
    
    let menu_id = state.database.add_menu(menu);
    
    Ok(Json(serde_json::json!({
        "success": true,
        "id": menu_id,
        "message": "菜单创建成功"
    })))
}

#[axum::debug_handler]
async fn get_menu_tree(
    State(state): State<Arc<AppState>>,
) -> Json<Vec<modules::database::Menu>> {
    Json(state.database.get_menu_tree())
}

#[axum::debug_handler]
async fn get_menu(
    State(state): State<Arc<AppState>>,
    Path(id): Path<i64>,
) -> Result<Json<modules::database::Menu>, StatusCode> {
    match state.database.get_menu(id.try_into().unwrap()) {
        Some(menu) => Ok(Json(menu)),
        None => Err(StatusCode::NOT_FOUND),
    }
}

#[axum::debug_handler]
async fn update_menu(
    State(state): State<Arc<AppState>>,
    Path(id): Path<i64>,
    Json(request): Json<UpdateMenuRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    let menu_id = id.try_into().unwrap();
    if let Some(mut menu) = state.database.get_menu(menu_id) {
        if let Some(name) = request.name {
            menu.menu_name = name;
        }
        if let Some(path) = request.path {
            menu.menu_path = Some(path);
        }
        if let Some(icon) = request.icon {
            menu.menu_icon = Some(icon);
        }
        if let Some(parent_id) = request.parent_id {
            menu.parent_id = Some(parent_id as i32);
        }
        if let Some(sort_order) = request.sort_order {
            menu.sort_order = sort_order;
        }
        menu.updated_at = OffsetDateTime::now_utc();
        
        if state.database.update_menu(menu_id, menu) {
            Ok(Json(serde_json::json!({
                "success": true,
                "message": "菜单更新成功"
            })))
        } else {
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

#[axum::debug_handler]
async fn delete_menu(
    State(state): State<Arc<AppState>>,
    Path(id): Path<i64>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    if state.database.delete_menu(id.try_into().unwrap()) {
        Ok(Json(serde_json::json!({
            "success": true,
            "message": "菜单删除成功"
        })))
    } else {
        Err(StatusCode::NOT_FOUND)
    }
}

// 通信系统处理器
#[axum::debug_handler]
async fn list_services(
    State(state): State<Arc<AppState>>,
) -> Json<Vec<modules::interfaces::ServiceInfo>> {
    let services = state.communication_manager.get_service_registry().get_all_services();
    Json(services)
}

#[axum::debug_handler]
async fn health_check_services(
    State(state): State<Arc<AppState>>,
) -> Json<serde_json::Value> {
    let results = state.communication_manager.get_service_registry().health_check().await;
    Json(serde_json::json!({
        "services": results,
        "timestamp": OffsetDateTime::now_utc().unix_timestamp()
    }))
}